<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\CityService;
use think\facade\View;

class City extends Diluma
{
    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return \think\response\Json
     */
    public function getCityList(){
        $service = new CityService();
        $items = $service->getCityList();
        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 编辑城市信息
     * @return \think\response\Json
     */
    public function edit(){
        $service = new CityService();
        $provinceItems = $service->getCitys(0);
        if($this->request->isPost()) {
            $id = $this->request->post('field.id');
            if($id <= 0){
                return $this->error('id不正确');
            }
            $post = $this->request->post();
            $data = [
                'title_name' => $post['field']['title_name'],
                'parent_id' => $post['field']['parent_id'],
                'id' => $id
            ];

            return $service->updateOrInsert($data);
        } else {    //非提交操作
            $id = (int)$this->request->get('id');
            if($id <= 0){
                return json(['code'=>1, 'msg'=>'参数异常']);
            }
            $data = $service->getOne($id);
            $data['province_list'] = $provinceItems;
            $provinceId = $service->getCityParentId($data['parent_id']);
            if($provinceId){
                $data['province_id'] = $provinceId;
                $data['city_list'] = $service->getCitys($data['province_id']);
            } else{
                $data['province_id'] = $data['parent_id'];
                $data['city_list'] = [];
            }

            View::assign('data', $data);
            return View::fetch();
        }
    }

    /**
     * 获取城市列表
     * @return \think\response\Json
     */
    public function getCitys(){
        $post = $this->request->post();
        if(empty($post['province_id'])){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        $service = new CityService();
        return $service->getCitys((int)$post['province_id']);
    }
}